import React, { Component } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'

import { reqCategory, reqAddOrUpdateProduct } from '../../api/admin'
import PicturesWall from './PicturesWall'

import RichTextEditor from './RichTextEditor'

import {
  Card,
  Form,
  Input,
  Button,
  Cascader,
  message
} from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
const { TextArea } = Input;


function annoyCom (MessCom) {
  return (props) => {
    let navigate = useNavigate()
    let loaction = useLocation()
    return <MessCom navigate={navigate} loaction={loaction} />
  }
}

class ProductAddOrUpdate extends Component {
  state = {
    optionLists: [],
  }

  myRef = React.createRef()
  detailRef = React.createRef()

  initOptions = async (categorys) => {
    //返回一个对象
    const optionLists = categorys.map(item => ({
      value: item._id,
      label: item.name,
      isLeaf: false
    }))
    //如果是一个二级分类商品的更新
    const { isUpdate, product } = this
    const { pCategoryId } = product
    if (isUpdate && pCategoryId !== '0') {
      const subCategorys = await this.getCategorys(pCategoryId)
      const childOptions = subCategorys.map(item => ({ //加一个小括号，返回的就是一个对象
        value: item._id,
        label: item.name,
        isLeaf: true
      }))
      //关联到对应的一级option上
      //先找到一级options
      const targetOption = optionLists.find(option => option.value === pCategoryId)
      targetOption.children = childOptions
    }
    this.setState({
      optionLists
    })
  }
  //  async函数的返回值是一个新的promise对象, promise的结果和值由async的结果来决定

  getCategorys = async (parentId) => {
    const result = await reqCategory(parentId)
    if (result.status === 0) {
      const categorys = result.data
      if (parentId === 0) {
        //一级分类
        this.initOptions(categorys)
      } else {
        return categorys
      }

    }
  }

  onFinish = async (values) => {
    console.log(values);
    const { name, desc, price, categoryIds } = values
    let pCategoryId, categoryId
    if (categoryIds.length === 1) {
      pCategoryId = '0'
      categoryId = categoryIds[0]
    } else {
      pCategoryId = categoryIds[0]
      categoryId = categoryIds[1]
    }
    const imgs = this.myRef.current.getImgs()
    const detail = this.detailRef.current.getDetail()
    const product = { name, desc, price, imgs, detail, pCategoryId, categoryId }
    if (this.isUpdate) {
      //如果是更新
      product._id = this.product._id
    }
    const result = await reqAddOrUpdateProduct(product)
    if (result.status === 0) {
      message.success(`${this.isUpdate ? '更新' : '添加'}商品成功！`)
      this.props.navigate('/product')
    } else {
      message.error(`${this.isUpdate ? '更新' : '添加'}商品失败！`)
    }
    console.log(imgs, detail);
  }

  validatePrice = async (rule, value) => {
    if (value * 1 <= 0) {
      throw new Error('输入的价格不能小于0')
    }
  }
  loadData = async (selectedOptions) => {
    //得到选择的option对象
    const targetOption = selectedOptions[selectedOptions.length - 1];
    console.log(targetOption);
    //显示loading
    targetOption.loading = true;

    //根据选中的分类，请求获取二级分类列表
    const subCategorys = await this.getCategorys(targetOption.value)
    targetOption.loading = false;
    if (subCategorys && subCategorys.length > 0) { //有二级分类
      const childOptions = subCategorys.map(item => ({ //加一个小括号，返回的就是一个对象
        value: item._id,
        label: item.name,
        isLeaf: true
      }))
      targetOption.children = childOptions
    } else {  //当前选中的分类没有二级分类
      targetOption.isLeaf = true
    }
    // 模拟请求异步获取二级列表

    this.setState({
      optionLists: [...this.state.optionLists]
    })
  };

  //如何判断是修改还是更新
  UNSAFE_componentWillMount () {
    const product = this.props.loaction.state
    this.isUpdate = !!product
    this.product = product || {}

  }

  componentDidMount () {
    this.getCategorys(0)
  }

  render () {
    const { isUpdate } = this
    const {
      name,
      desc,
      price,
      imgs,
      detail,
      pCategoryId,
      categoryId,
    } = this.product;
    //用来接收级联分类ID的数组
    const categoryIds = []
    if (isUpdate) {
      //   console.log("pCategoryId", pCategoryId);
      if (pCategoryId !== "0") {
        categoryIds.push(pCategoryId);
      }
    }
    categoryIds.push(categoryId);
    console.log(categoryIds);
    const title = (
      <div>
        <ArrowLeftOutlined style={{ color: '#1CA579' }} onClick={() => this.props.navigate('/product')} />
        <span style={{ marginLeft: 15 }}>{isUpdate ? '修改商品' : '添加商品'}</span>
      </div>
    )
    // 表单布局
    const formItemLayout = {
      labelCol: {
        xs: { span: 2 },
        sm: { span: 2 },
      },
      wrapperCol: {
        xs: { span: 4 },
        sm: { span: 8 },
      },
    };

    return (
      <div>
        <Card title={title}>
          <Form
            {...formItemLayout}
            onFinish={this.onFinish}
          >
            <Form.Item
              name="name"
              label="商品名称:"
              initialValue={name}
              rules={[
                {
                  required: true,
                  message: '商品名称必须填写!',
                },
              ]}
            >
              <Input placeholder="请输入商品名称" />
            </Form.Item>
            <Form.Item
              name="desc"
              label="商品描述:"
              initialValue={desc}
              rules={[
                {
                  required: true,
                  message: '商品描述必须填写!',
                },
              ]}
            >
              <TextArea autosize={{ minRows: 2, maxRows: 6 }} placeholder="请输入商品描述" />
            </Form.Item>
            <Form.Item
              name="price"
              label="商品价格:"
              initialValue={price}
              rules={[
                {
                  required: true,
                  message: '商品价格必须填写!',
                },
                { validator: this.validatePrice }
              ]}
            >
              <Input type="number" addonAfter="元" placeholder="请输入商品价格" />
            </Form.Item>
            <Form.Item
              name="categoryIds"
              label="商品分类:"
              initialValue={categoryIds}
              rules={[
                {
                  required: true,
                  message: '商品分类必须选择!',
                }
              ]}
            >
              <Cascader
                options={this.state.optionLists}
                loadData={this.loadData}
                placeholder="请指定商品分类"
              />
            </Form.Item>
            <Form.Item
              name="pidture"
              label="商品图片:"
            >
              <PicturesWall ref={this.myRef} imgs={imgs} />
            </Form.Item>
            <Form.Item
              name="details"
              label="商品详情:"
              labelCol={{ span: 2 }}
              wrapperCol={{ span: 20 }}
            >
              <RichTextEditor ref={this.detailRef} detail={detail} />
            </Form.Item>
            <Form.Item >
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
}

export default annoyCom(ProductAddOrUpdate)